package com.niiwoo.civet.trade.service.dubbo.credit;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.curator.shaded.com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.trade.constant.TradeCommonConstant;
import com.niiwoo.civet.trade.dao.entity.credit.CreditInvestigationPerson;
import com.niiwoo.civet.trade.dao.entity.credit.CreditProject;
import com.niiwoo.civet.trade.dto.request.credit.GetInvestigationProjectListRequest;
import com.niiwoo.civet.trade.dto.response.credit.InvestigationProjectDTO;
import com.niiwoo.civet.trade.dto.response.credit.InvestigationStatisticsDTO;
import com.niiwoo.civet.trade.service.credit.InvestigationDubboService;
import com.niiwoo.civet.trade.service.local.credit.CreditInvestigationPersonService;
import com.niiwoo.civet.trade.service.local.credit.CreditProjectService;
import com.niiwoo.tripod.provider.dto.response.PageResponseDTO;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service(version = "1.0.0", validation = "true")
public class InvestigationDubboServiceImpl implements InvestigationDubboService {

	private static final String MSG = "【借用借-我的尽调】";
	
	@Autowired
	private CreditProjectService creditProjectService;

	@Autowired
	private CreditInvestigationPersonService creditInvestigationPersonService;

	@Override
	public InvestigationStatisticsDTO getInvestigationStatistics(String userId) {
		
		try {
			InvestigationStatisticsDTO investigationStatisticsDTO = new InvestigationStatisticsDTO();
			
			// 累计尽调收益
			BigDecimal accruedIncomeAmount = creditInvestigationPersonService.getAccruedIncomeAmount(userId);
			
			// 最近3个月累计尽调收益
			BigDecimal latest3accruedIncomeAmount = creditInvestigationPersonService.getLatest3AccruedIncomeAmount(userId);
			
			// 有效的尽调笔数
			Integer investigationTotalNumber = creditInvestigationPersonService.getInvestigationTotalNumber(userId);
			
			accruedIncomeAmount = accruedIncomeAmount.setScale(TradeCommonConstant.NUMBER_PRECISION_TWO, BigDecimal.ROUND_HALF_EVEN);
			latest3accruedIncomeAmount = latest3accruedIncomeAmount.setScale(TradeCommonConstant.NUMBER_PRECISION_TWO, BigDecimal.ROUND_HALF_EVEN);
			
			investigationStatisticsDTO.setAccruedIncomeAmount(accruedIncomeAmount);
			investigationStatisticsDTO.setLatest3MonthIncomeAmount(latest3accruedIncomeAmount);
			investigationStatisticsDTO.setInvestigationTotalNumber(investigationTotalNumber);
			
			return investigationStatisticsDTO;
		} catch (Exception e) {
			log.error(MSG + "查询我的尽调详情异常，异常原因：" + e.getMessage() + "，请求参数：[userId:" + userId + "]");
			throw new RuntimeException("调用服务异常", e);
		}
	}

	@Override
	public PageResponseDTO<InvestigationProjectDTO> getInvestigationProjectPage(GetInvestigationProjectListRequest request) {
		try {
			return creditInvestigationPersonService.getInvestigationProjectPage(request.getUserId(), request.getPageNumber(), request.getPageSize());
		} catch (Exception e) {
			log.error(MSG + "查询尽调项目列表异常，异常原因：" + e.getMessage() + "，请求参数：" + JSONObject.toJSONString(request));
			throw new RuntimeException("调用服务异常", e);
		}
	}

	@Override
	public List<InvestigationProjectDTO> getInvestigationProjectList2(GetInvestigationProjectListRequest request) {
		// 查询有效的尽调记录
		List<CreditInvestigationPerson> creditInvestigationPersonList = creditInvestigationPersonService
				.getCreditInvestigationPersonList(request.getUserId(), request.getPageNumber(), request.getPageSize());
		if (CollectionUtils.isEmpty(creditInvestigationPersonList)) return Lists.newArrayList();
		
		// 尽调关联的项目信息
		List<Long> projectIdList = creditInvestigationPersonList.stream().map(CreditInvestigationPerson::getProjectId).distinct()
				.collect(Collectors.toList());
		if (CollectionUtils.isEmpty(projectIdList)) return Lists.newArrayList();
		
		List<CreditProject> creditProjectList = creditProjectService.getCreditProjectByProjectIdList(projectIdList);
		if (CollectionUtils.isEmpty(creditProjectList)) return Lists.newArrayList();
		
		// 转化成DTO对象
		List<InvestigationProjectDTO> investigationProjectDTOList = Lists.newArrayList();
		for (CreditProject creditProject : creditProjectList) {
			InvestigationProjectDTO investigationProjectDTO = new InvestigationProjectDTO();
			cloneProperties(creditProject, investigationProjectDTO);
			investigationProjectDTOList.add(investigationProjectDTO);
		}
		return investigationProjectDTOList;
	}
	
	/**
	 * 复制属性
	 * 
	 * @param creditProject	信用借项目信息
	 * @param investigationProjectDTO	尽调项目DTO
	 */
	private void cloneProperties(CreditProject creditProject, InvestigationProjectDTO investigationProjectDTO) {
		
		if (null == creditProject) return;
		
		investigationProjectDTO.setProjectId(creditProject.getProjectId());
		investigationProjectDTO.setBorrowUserId(creditProject.getBorrowUserId());
		investigationProjectDTO.setBorrowNickName(creditProject.getBorrowNickName());
		investigationProjectDTO.setBorrowHeadImg(creditProject.getBorrowHeadImg());
		investigationProjectDTO.setBorrowSex(creditProject.getBorrowSex());
		investigationProjectDTO.setTitle(creditProject.getTitle());
		investigationProjectDTO.setContractAmount(creditProject.getContractAmount());
		investigationProjectDTO.setGuaranteeRate(creditProject.getGuaranteeRate());
		investigationProjectDTO.setDeadline(creditProject.getDeadline());
		investigationProjectDTO.setProjectStatus(creditProject.getProjectStatus());
		investigationProjectDTO.setLoanCity(creditProject.getLoanCity());
		investigationProjectDTO.setLoanArea(creditProject.getLoanArea());
		investigationProjectDTO.setCreateTime(creditProject.getCreateTime());
	}
}